package com.coscon.shiro;


import com.coscon.common.SpringContextUtils;
import com.coscon.config.ApplicationStartup;
import com.coscon.enums.SessionKey;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;

import java.util.HashSet;
import java.util.Set;


@Slf4j
public class ShiroRealm extends AbstractOperatorAuthorizingRealmWithRpn {


  public ShiroRealm() {
    super();
  }

  @Override
  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
    log.debug("登录操作进行登录认证......");


    UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

    //用户输入的登录名
    String userLogonName = token.getUsername();
    String passpsw = new String(token.getPassword());

    log.debug("userLogonName=" + userLogonName);
    log.debug("passpsw=" + passpsw);
    ApplicationStartup applicationStartup= SpringContextUtils.getBeanByClass(ApplicationStartup.class);
    //临时设置个，后续需要从数据库中认证
    if(StringUtils.isNotBlank(userLogonName) && StringUtils.equalsIgnoreCase(userLogonName,applicationStartup.getAuthCode())
    ){
      Session session = SecurityUtils.getSubject().getSession();
      session.setAttribute(SessionKey.UserId.getKey(),userLogonName);
      return new SimpleAuthenticationInfo(token.getUsername(), token.getPassword(), getName());
    }else{
      throw new AuthenticationException("ERROR:认证失败！");
    }

  }



  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    log.info("登录验证后进行权限认证....");
    /* 这里编写授权代码 */
    Set<String> roleNames = new HashSet<String>();
    Set<String> permissions = new HashSet<String>();

    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames);
    info.setStringPermissions(permissions);
    return info;
  }


  /**
   * 更新用户授权信息缓存.
   */
  public void clearCachedAuthorizationInfo(String principal) {
    SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());
    clearCachedAuthorizationInfo(principals);
  }

  /**
   * 清除所有用户授权信息缓存.
   */
  public void clearAllCachedAuthorizationInfo() {
    Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
    if (cache != null) {
      for (Object key : cache.keys()) {
        cache.remove(key);
      }
    }
  }


}
